#include "stdafx.h"
#include "HeaderCtrlEx.h"

IMPLEMENT_DYNAMIC(HeaderCtrlEx, CHeaderCtrl)

BEGIN_MESSAGE_MAP(HeaderCtrlEx, CHeaderCtrl)
    ON_NOTIFY_REFLECT(NM_CUSTOMDRAW, &HeaderCtrlEx::OnNMCustomdraw)
    ON_MESSAGE(HDM_LAYOUT, &HeaderCtrlEx::OnLayout)
END_MESSAGE_MAP()

void HeaderCtrlEx::OnNMCustomdraw(NMHDR* pNMHDR, LRESULT* pResult)
{
    // ref: https://stackoverflow.com/questions/28766659/changing-mfc-list-control-header-color
    LPNMCUSTOMDRAW pNMCD = reinterpret_cast<LPNMCUSTOMDRAW>(pNMHDR);
    // TODO: Add your control notification handler code here
    *pResult = CDRF_DODEFAULT;

    if (pNMCD->dwDrawStage == CDDS_PREPAINT)
    {
        CDC* pDC = CDC::FromHandle(pNMCD->hdc);
        CRect rect(0, 0, 0, 0);
        GetClientRect(&rect);
        pDC->FillSolidRect(&rect, RGB(215, 235, 226));

        *pResult = CDRF_NOTIFYITEMDRAW;
    }
    else if (pNMCD->dwDrawStage == CDDS_ITEMPREPAINT)
    {
        HDITEM hditem;
        TCHAR buffer[MAX_PATH] = { 0 };
        SecureZeroMemory(&hditem, sizeof(HDITEM));
        hditem.mask = HDI_TEXT;
        hditem.pszText = buffer;
        hditem.cchTextMax = MAX_PATH;
        GetItem(pNMCD->dwItemSpec, &hditem);

        CDC* pDC = CDC::FromHandle(pNMCD->hdc);
        pDC->SetTextColor(RGB(0, 0, 0));
        pDC->SetBkColor(RGB(215, 235, 226));

        //CFont m_pFont;
        //m_pFont.CreateFont(ConvertWithDPIRatio(31),
        //    0, 0, 0, FW_MEDIUM,
        //    FALSE, FALSE,
        //    0,
        //    ANSI_CHARSET,              // nCharSet
        //    OUT_DEFAULT_PRECIS,        // nOutPrecision
        //    CLIP_DEFAULT_PRECIS,       // nClipPrecision
        //    DEFAULT_QUALITY,           // nQuality
        //    DEFAULT_PITCH | FF_SWISS, _T("Arial"));
        //pDC->SelectObject(m_pFont);
        CString str(buffer);
        CRect rect = pNMCD->rc;
        rect.OffsetRect(6, 0);
        pDC->DrawText(str, CRect(rect), DT_SINGLELINE | DT_VCENTER);
        *pResult = CDRF_SKIPDEFAULT;
    }
}

/*
*   Describe: Change the height of table header
*   Author  : Canliang Wu
*   Date    : 2021/12/15
*/
LRESULT HeaderCtrlEx::OnLayout(WPARAM wParam, LPARAM lParam)
{
    LRESULT lResult = CHeaderCtrl::DefWindowProc(HDM_LAYOUT, 0, lParam);
    HD_LAYOUT& hdl = *(HD_LAYOUT*)lParam;

    RECT* prc = hdl.prc;            // The table list rectangle
    WINDOWPOS* pwpos = hdl.pwpos;   // The table header rectangle

    int nHeight = (int)(pwpos->cy * 1.3);
    
    pwpos->cy = nHeight;            // New table header height
    //pwpos->x += 3;

    prc->top = nHeight;             // Decreases the table list height on the table header height

    return lResult;
}



